import { Core } from "@/comm/Core";
import { URL_LOGIN_TWITTER, URL_METAMASK } from "@/comm/api";
import { get, post } from "@/comm/request";
import { toast } from "@/components/toast/toast";
import { useUser } from "@/stores/user";
import { useAccount } from "@/stores/account";
import { ref } from "vue";
import Web3 from "web3"
import detectProvider from '@metamask/detect-provider';
const HOST = "https://dev.chainingview.io";
// const HOST = import.meta.env.VITE_URL_CALLBACK;
export const useLogin = function () {
    const account = useAccount();
    const accountAddress = ref('');
    let user = useUser()
    const loginMetaMask = async () => {
        let param = {}
        // console.log(provider.isMetaMask);
        // console.log(provider, "providerprovider");
        let recommendCode = localStorage.getItem("code");
        if (account.isMetaMask) {
            const provider: any = await detectProvider();
            // 连接到MetaMask提供者
            try {
                let temp = await provider.request({ method: 'eth_requestAccounts' });
                // 请求用户授权
                const accounts = await provider.request({ method: 'eth_accounts' });
                const address = accounts[0];
                const networkId = await provider.request({ method: 'eth_chainId' });
                console.log(networkId, "networkId");
                // let netId = Web3.utils.hexToNumberString(networkId)
                let netId = ''
                // if (onlineId != '1') {
                //     user.switchNetwork(1)
                // }
                user.listenNetwork()
                // const networkVersion = await ethereum.request({ method: 'net_version' });
                // console.log(networkVersion, "networkVersion");
                // const chainData = await ethereum.request({ method: 'eth_getChainParams' });
                // console.log(chainData, "chainData");
                param = {
                    address,
                    recommendCode,
                    netId
                }
                let res: any = await post(URL_METAMASK, param, true)
                if (res.code == 200) {
                    if (res.data.firstLogin) {
                        account.changePopRegisterSuccess(true);
                    }
                    toast(res.info);
                    localStorage.setItem("token", res.data.token);
                    account.changePopLogin(false);
                    account.changePopLogin(false);
                    account.changePopRegister(false);
                    let userInfo = await user.getUserInfo();

                }
            } catch (error) {
                console.error('用户拒绝了授权', error);
            }
            // 用户已授权，可以进行交互
        } else {
            // MetaMask未安装或未授权
            // 提示用户安装MetaMask插件或授权访问
            toast("Please install MetaMask.");

        }
    }

    const loginGoogle = () => {
        let url =
            "https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/userinfo.email&include_granted_scopes=true&response_type=token&state=3EAB37D9D5310BFE&redirect_uri="
            + HOST +
            "/jgoogle.html&client_id=809263687381-ofm0eu28sekcj9449r9ueou4b3ksd74a.apps.googleusercontent.com";
        console.log("url", url)
        // alert(url)

        // "/oauth/google&client_id=196315512392-h621tm4818ml5bl6ljv5lako4d17bac6.apps.googleusercontent.com";

        if (location.href.includes("localhost")) {
            url = "/jump.html"
        }

        login(url);
        // window.open(url, "_self");
    };

    const loginTwitter = () => {
        get(URL_LOGIN_TWITTER).then((res: any) => {
            console.log("URL_LOGIN_TWITTER", res);
            if (res.code == 200) {
                login(res.data);
            } else {
                toast(res.info);
            }
        });
    };
    const login = (url: string) => {
        console.log(url, "login");
        const windowWidth = window.innerWidth;
        const windowHeight = window.innerHeight;
        const w = 400;
        const h = 400;
        const left = (windowWidth - w) / 2;
        const top = (windowHeight - h) / 2;
        window.open(url, "newWindow", `width=${w},height=${h},left=${left},top=${top}`);

        setTimeout(() => {
            account.changePopLogin(false);
        }, 900);
    };
    return {
        loginGoogle,
        loginTwitter,
        loginMetaMask,
    };
};

// https://accounts.google.com/o/oauth2/v2/auth?scope=https://www.googleapis.com/auth/userinfo.email&include_granted_scopes=true&response_type=token&state=3EAB37D9D5310BFE&redirect_uri=http://chainingview.natapp1.cc/oauth/google&client_id=196315512392-h621tm4818ml5bl6ljv5lako4d17bac6.apps.googleusercontent.com
